$(function() {

    $(".form-myt-purchase-purchase-order-bpmInput").data("formOptions", {
        updateTotalAmount : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-purchase-purchase-order-bpmInput");
            var userData = {
                "commodity.display" : "合计："
            };
            //更新表格汇总统计数据
            userData.quantity = $grid.jqGrid('sumColumn', 'quantity');
            userData.amount = $grid.jqGrid('sumColumn', 'amount');
            userData.deliveryAmount = $grid.jqGrid('sumColumn', 'deliveryAmount');
            userData.discountAmount = $grid.jqGrid('sumColumn', 'discountAmount');
            userData.originalAmount = $grid.jqGrid('sumColumn', 'originalAmount');
            userData.costAmount = $grid.jqGrid('sumColumn', 'costAmount');
            $grid.jqGrid("footerData", "set", userData, true);
            var totalAmount = userData.deliveryAmount + userData.amount;
            $form.find(".span-total-amount").html(totalAmount);
            $form.setFormDatas({
                amount : userData.amount,
                totalDiscountAmount : userData.discountAmount,
                totalDeliveryAmount : userData.deliveryAmount,
                totalAmount : totalAmount
            });

        },
        bindEvents : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-purchase-purchase-order-bpmInput");
            //按金额自动分摊折扣金额
            $form.find(".btn-discount-by-amount").click(function() {
                if ($grid.jqGrid("isEditingMode", true)) {
                    return false;
                }
                //按照“原价金额”的比率计算更新每个行项的折扣额，注意最后一条记录需要以减法计算以修正小数精度问题
                var totalDiscountAmount = $form.find("input[name='totalDiscountAmount']").val();
                var totalOriginalAmount = $grid.jqGrid('sumColumn', 'originalAmount');
                var perDiscountAmount = MathUtil.mul(MathUtil.div(totalDiscountAmount, totalOriginalAmount, 5), 100);
                var lastrowid = null;
                var tempDiscountAmount = 0;
                var ids = $grid.jqGrid("getDataIDs");
                $.each(ids, function(i, id) {
                    var rowdata = $grid.jqGrid("getRowData", id);
                    if (rowdata['gift'] != 'true' && rowdata['commodity.id'] != '') {
                        rowdata['discountRate'] = perDiscountAmount;
                        $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'discountRate');
                        $grid.jqGrid('setRowData', id, rowdata);
                        tempDiscountAmount = MathUtil.add(tempDiscountAmount, rowdata['discountAmount']);
                        lastrowid = id;
                    }
                });
                //最后一条记录需要以减法计算以修正小数精度问题
                if (lastrowid) {
                    var rowdata = $grid.jqGrid("getRowData", lastrowid);
                    rowdata['discountAmount'] = MathUtil.sub(totalDiscountAmount, MathUtil.sub(tempDiscountAmount, rowdata['discountAmount']));
                    $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'discountAmount');
                    $grid.jqGrid('setRowData', lastrowid, rowdata);
                }

                $form.data("formOptions").updateTotalAmount.call($form);

            });
            //按金额自动分摊运费
            $form.find(".btn-delivery-by-amount").click(function() {
                if ($grid.jqGrid("isEditingMode", true)) {
                    return false;
                }
                //按照“原价金额”的比率计算更新每个行项的折扣额，注意最后一条记录需要以减法计算以修正小数精度问题
                var totalDeliveryAmount = $form.find("input[name='totalDeliveryAmount']").val();
                var totalOriginalAmount = $grid.jqGrid('sumColumn', 'originalAmount');

                var perDeliveryAmount = MathUtil.div(totalDeliveryAmount, totalOriginalAmount, 5);
                var lastrowid = null;
                var tempDeliveryAmount = 0;
                var ids = $grid.jqGrid("getDataIDs");
                $.each(ids, function(i, id) {
                    var rowdata = $grid.jqGrid("getRowData", id);
                    if (rowdata['commodity.id'] != '') {
                        rowdata['deliveryAmount'] = MathUtil.mul(perDeliveryAmount, rowdata['originalAmount']);
                        $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'deliveryAmount');
                        $grid.jqGrid('setRowData', id, rowdata);
                        tempDeliveryAmount = MathUtil.add(tempDeliveryAmount, rowdata['deliveryAmount']);
                        lastrowid = id;
                    }
                });

                //最后一条记录需要以减法计算以修正小数精度问题
                if (lastrowid) {
                    var rowdata = $grid.jqGrid("getRowData", lastrowid);
                    rowdata['deliveryAmount'] = MathUtil.sub(totalDeliveryAmount, MathUtil.sub(tempDeliveryAmount, rowdata['deliveryAmount']));

                    $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'deliveryAmount');
                    $grid.jqGrid('setRowData', lastrowid, rowdata);
                }

                $form.data("formOptions").updateTotalAmount.call($form);

            });
            
            
            // 从销售单选取
            $form.find(".btn-select-sale-delivery").click(function() {
                var $saleDeliveryId = $form.find("input[name='saleDelivery.id']");
                var saleDeliveryId = $saleDeliveryId.val();
                if (saleDeliveryId != '') {
                    if (confirm("一个采购订单只允许从单个销售单选取，重新选取将清空当前相关数据以新选择销售单数据覆盖，确认继续？")) {
                        $grid.clearGridData();
                        $form.data("formOptions").updateTotalAmount.call($form);
                    }else{
                        return;
                    }
                }

                $(this).popupDialog({
                    url : WEB_ROOT + '/myt/sale/sale-delivery!forward?_to_=selectSaleDelivery',
                    title : '选取销售单',
                    callback : function(data) {
                        var master = data.master;
                        var rows = data.rows;
                        $saleDeliveryId.val(master.id);
                        $form.find("input[name='storageMode'][value='"+master['storageMode']+"']").attr("checked",'checked');
                        $form.setFormDatas({
                            // 'title' : "[" + master['reserveDeliveryTime'].substr(0, 7) + "]" + master['boxOrder.title'],
                             
                        }, true);

                        $.each(rows, function(i, row) {
                            console.info(row);
                            
                            var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                            var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                            for(i=0; i<ids.length; i++){
                                var tableRow = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                                if(row['commodity.sku'] == tableRow['commodity.sku']){
                                    // SKU一致即认为是同一商品
                                    existRowId = ids[i];
                                    break;
                                }
                            }
                            
                            if(existRowId){
                                // 如果商品已存在，累加商品数量
                                var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                                myrowdata.quantity = Number(row.quantity) + Number(myrowdata.quantity);
                                $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                                $grid.jqGrid("setRowData", existRowId, myrowdata);
                            }else{
                                // 商品不存在，新增行
                                row['saleDeliveryDetail.id'] = row['id'];
                                $grid.data("gridOptions").calcRowAmount.call($grid, row);
                                var newid = $grid.jqGrid('insertNewRowdata', row);// 插入行
                                // 计算并设置行项号
                                var idx = $grid.find("tr[id='" + newid + "'] >td.jqgrid-rownum").html().trim();
                                $grid.jqGrid('setRowData', newid, {
                                    subVoucher : 100 + idx * 10
                                });
                            }
                            
                            // 计算汇总数据
                            $form.data("formOptions").updateTotalAmount.call($form);
                        });
                    }
                })
            });
            
            
            //扫描枪输入处理中用到的 自动填充商品行项方法
            var completeCommodity = function(item){
                var rowdata = item;
                console.info(rowdata.sku);
                var ids = $grid.jqGrid('getDataIDs');
                var targetRowdata = null;
                var targetRowid = null;
                $.each(ids, function(i, id) {
                    var item = $grid.jqGrid('getRowData', id);
                    if (item['commodity.sku'] == rowdata['sku']) {
                        targetRowid = id;
                        targetRowdata = item;
                        return false;
                    }
                });

                if (targetRowdata) {
                    targetRowdata.quantity = Number(targetRowdata.quantity) + 1;
                    $grid.data("gridOptions").calcRowAmount.call($grid, targetRowdata);
                    $grid.jqGrid('setRowData', targetRowid, targetRowdata);
                } else {
                    var newdata = {
                        'commodity.id' : rowdata.id,
                        'commodity.sku' : rowdata.sku,
                        'measureUnit' : rowdata.measureUnit,
                        'storageLocation.id' : rowdata['defaultStorageLocation.id'],
                        'commodity.display' : rowdata.display,
                        'discountRate' : 0,
                        'taxRate' : 0,
                        'quantity' : 1
                    }
                    newdata['price'] = rowdata['lastPurchasePrice'];
                    $grid.data("gridOptions").calcRowAmount.call($grid, newdata);
                    $grid.jqGrid('insertNewRowdata', newdata);
                }
                $form.data("formOptions").updateTotalAmount.call($form);
            }
            //扫描枪输入处理
            $barcodeInp = $form.find("input[name='barcode']");
            $barcodeInp.barcodeScanSupport({
                onEnter : function() {
                    var code = $(this).val();
                    if (code != '') {
                        var data = Biz.queryCacheCommodityDatas(code);
                        if (data && data.length > 0) {
                            var rowdata = data[0];
                            completeCommodity(rowdata);
                        }
                        $(this).blur().focus();
                    }
                }
            });
            // 条码框的自动提示（如果一个条码查询返回多个商品，则显示商品列表让用户进一步选取商品）
            $barcodeInp.autocomplete({
                source : function(request, response) {
                    var data = Biz.queryCacheCommodityDatas(request.term);
                    // 如果没有匹配到商品，或者只匹配到一条商品，那么不显示下拉列表
                    if(data.length < 2){
                        return response({});
                    }
                    return response(data);
                },
                minLength : 2,
                select : function(event, ui) {
                    var item = ui.item;
                    //this.value = item.display;
                    // 调用填充行项方法
                    completeCommodity(item);
                    
                    event.stopPropagation();
                    event.preventDefault();
                    return false;
                }
            });

        }
    });

    $(".grid-myt-purchase-purchase-order-bpmInput").data("gridOptions", {
        calcRowAmount : function(rowdata, src) {

            rowdata['originalAmount'] = MathUtil.mul(rowdata['price'], rowdata['quantity']);
            //src=='deliveryAmount'的时候不计算折扣，避免已计算好的折扣再次计算出现精度问题
            if (src != 'deliveryAmount') {
                if (src == 'discountAmount') {
                    rowdata['discountRate'] = MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'], 5) * 100;
                    rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
                } else if (src == 'amount') {
                    rowdata['discountAmount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['amount']);
                    rowdata['discountRate'] = MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'], 5) * 100;
                } else {
                    rowdata['discountAmount'] = MathUtil.div(MathUtil.mul(rowdata['discountRate'], rowdata['originalAmount']), 100);
                    rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
                }
            }
            rowdata['costAmount'] = MathUtil.add(rowdata['amount'], rowdata['deliveryAmount']);
            rowdata['costPrice'] = MathUtil.div(rowdata['costAmount'], rowdata['quantity'], 2);

        },
        updateRowAmount : function(src) {

            var $grid = $(this);
            var rowdata = $grid.jqGrid("getEditingRowdata");
            $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, src);
            $grid.jqGrid("setEditingRowdata", rowdata);

        },
        batchEntitiesPrefix : "purchaseOrderDetails",
        url : function() {
            var pk = $(this).attr("data-pk");
            if (pk) {
                return WEB_ROOT + "/myt/purchase/purchase-order!purchaseOrderDetails?id=" + pk + "&clone=" + $(this).attr("data-clone");
            }
        },
        colModel : [ {
            label : '所属订单主键',
            name : 'purchaseOrder.id',
            hidden : true,
            hidedlg : true,
            editable : true,
            formatter : function(cellValue, options, rowdata, action) {
                var pk = $(this).attr("data-pk");
                return pk ? pk : "";
            }
        }, {
            name : 'saleDeliveryDetail.id',
            hidden : true,
            hidedlg : true,
            editable : true
        },  {
            label : '商品主键',
            name : 'commodity.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodity.sku',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            label : '行项号',
            name : 'subVoucher',
            width : 50,
            editable : true,
            editrules : {
                required : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $el = $(elem);
                    if ($el.val() == '') {
                        var $jqgrow = $el.closest(".jqgrow");
                        var idx = $jqgrow.parent().find(".jqgrow:visible").index($jqgrow);
                        $el.val(100 + idx * 10);
                    }
                }
            },
            align : 'center'
        }, {
            label : '采购商品',
            name : 'commodity.display',
            editable : true,
            width : 200,
            editrules : {
                required : true
            },
            editoptions : {
                placeholder : '输入商品信息提示选取或双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    // 弹出框的选取回调函数
                    var selectCommodity = function(item) {
                        
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        
                        var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                        var oldQuantity = null;// 如果是已经选择过的商品，那么这是哪个商品的数量
                        for(i=0; i<ids.length; i++){
                            var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            if(item['sku'] == row['commodity.sku']){
                                // SKU一致即认为是同一商品
                                existRowId = ids[i];
                                oldQuantity = row.quantity;
                                break;
                            }
                        }
                        
                        if(existRowId){
                            $grid.jqGrid("setRowData", existRowId, {
                                'quantity' : Number(oldQuantity)+1
                            });
                            var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            $grid.jqGrid("setRowData", existRowId, myrowdata);
                        }else{
                            var myrowdata = {
                                    'commodity.sku' : item['sku'],//商品唯一性标识
                                    'commodity.id' : item.id,
                                    'commodity.barcode' : item.barcode,
                                    'price' : item.price,
                                    'measureUnit' : item.measureUnit,
                                    'commodity.display' : item.title,
                                    'storageLocation.id' : item['defaultStorageLocation.id'],
                                    'quantity' : 1,
                                    'discountRate' : 0,
                                    'deliveryAmount' : 0
                            };
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            existRowId = $grid.jqGrid("insertNewRowdata", myrowdata);
                        }
                        
                        // 整个Form相关金额字段更新
                        var $form = $grid.closest("form");
                        $form.data("formOptions").updateTotalAmount.call($form);
                        
                        // 计算并设置行项号
                        var idx = $grid.find("tr[id='" + existRowId + "'] >td.jqgrid-rownum").html().trim();
                        $grid.jqGrid('setRowData', existRowId, {
                            subVoucher : 100 + idx * 10
                        });
                    }
                    // 自动完成框的选取回调函数
                    var autocompleteSelectCommodity = function(item) {
                        
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        
                        var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                        for(i=0; i<ids.length; i++){
                            var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            if(item['sku'] == row['commodity.sku']){
                                // SKU一致即认为是同一商品
                                existRowId = ids[i];
                                break;
                            }
                        }
                        
                        if(existRowId){
                            var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                            alert("所选商品已存在[ "+myrowdata.subVoucher+" | "+myrowdata['commodity.display']+" ]，请直接编辑数量字段。");
                            return;
                        }else{
                            var myrowdata = {
                                    'commodity.sku' : item['sku'],//商品唯一性标识
                                    'commodity.id' : item.id,
                                    'commodity.barcode' : item.barcode,
                                    'price' : item.price,
                                    'measureUnit' : item.measureUnit,
                                    'commodity.display' : item.title,
                                    //'storageLocation.id' : item['defaultStorageLocation.id'],
                                    'quantity' : 1,
                                    'discountRate' : 0,
                                    'deliveryAmount' : 0
                            };
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            existRowId = $grid.jqGrid("setEditingRowdata", myrowdata);
                        }
                        
                        // 整个Form相关金额字段更新
                        var $form = $grid.closest("form");
                        $form.data("formOptions").updateTotalAmount.call($form);
                    }
                    $elem.dblclick(function() {
                        var rowdata = $grid.jqGrid("getEditingRowdata");
                        var $form = $grid.closest("form");
                        // var storageMode = $form.find("input[name='storageMode']:checked").val();
                        $(this).popupDialog({
                            url : WEB_ROOT + '/myt/md/commodity!forward?_to_=selectionMore',
                            title : '选取库存商品',
                            callback : function(item) {
                                selectCommodity(item);
                            }
                        })
                        // 多选模式双击弹出选取框之后，取消当前行编辑状态
                        $grid.closest("div.ui-jqgrid-view").find(".ui-pg-div span.ui-icon-cancel").click();
                    }).autocomplete({
                        autoFocus : true,
                        source : function(request, response) {
                            var data = Biz.queryCacheCommodityDatas(request.term);
                            return response(data);
                        },
                        minLength : 2,
                        select : function(event, ui) {
                            var item = ui.item;
                            this.value = item.display;

                            autocompleteSelectCommodity(item);
                            event.stopPropagation();
                            event.preventDefault();
                            return false;
                        },
                        change : function(event, ui) {
                            if (ui.item == null || ui.item == undefined) {
                                //$elem.val("");
                                $elem.focus();
                            }
                        }
                    }).focus(function() {
                        $elem.select();
                    });
                }
            },
            align : 'left'
        }, {
            label : '收货仓库',
            name : 'storageLocation.id',
            width : 150,
            editable : true,
            editrules : {
                required : true
            },
            stype : 'select',
            searchoptions : {
                value : Biz.getStockDatas()
            }
        }, {
            label : '单位',
            name : 'measureUnit',
            editable : true,
            width : 80
        }, {
            label : '数量',
            name : 'quantity',
            width : 80,
            formatter : 'number',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    if ($elem.val() == "") {
                        $elem.val(1)
                    }
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.closest("tr.jqgrow"));
                    });
                }
            },
            summaryType : 'sum',
            responsive : 'sm'
        }, {
            label : '单价',
            name : 'price',
            width : 80,
            formatter : 'currency',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.closest("tr.jqgrow"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '原价金额',
            name : 'originalAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        }, {
            label : '折扣率(%)',
            name : 'discountRate',
            width : 80,
            formatter : 'currency',
            editable : true,
            editrules : {
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '折扣额',
            name : 'discountAmount',
            width : 80,
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            align : 'right',
            responsive : 'sm'
        }, {
            label : '折后金额',
            name : 'amount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '分摊运费',
            name : 'deliveryAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    if ($elem.val() == "") {
                        $elem.val(0)
                    }
                    var $form = $elem.closest("form");
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.closest("tr.jqgrow"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '成本单价',
            name : 'costPrice',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        }, {
            label : '总成本',
            name : 'costAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        } ],
        footerrow : true,
        beforeInlineSaveRow : function(rowid) {
            var $grid = $(this);
            $grid.data("gridOptions").updateRowAmount.call($grid);
        },
        afterInlineSaveRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        afterInlineDeleteRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        userDataOnFooter : true
    });
});